package com.zr.chat;

import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/socket")
public class WebSocketChat {
	private static CopyOnWriteArraySet<WebSocketChat> websocket = new CopyOnWriteArraySet<WebSocketChat>();
	
	private Session session;
	
	@OnOpen
	public void onOpen(Session session){
		this.session = session;
		websocket.add(this);
	}
	
	@OnClose
	public void onClose(){
		websocket.remove(this);
	}
	
	@OnMessage
	public void onMessage(String message,Session session){
		for (WebSocketChat socketChat : websocket) {
			socketChat.session.getAsyncRemote().sendText(message);//异步
			//socketChat.session.getBasicRemote().sendText(message);//同步
		}
	}
	
	@OnError
	public void onError(Throwable error){
		//error.printStackTrace();
	}
}
